package com.nnnu.wsnackshop.controller.user;

import com.nnnu.wsnackshop.constant.MessageConstants;
import com.nnnu.wsnackshop.constant.StatusCodeConstants;
import com.nnnu.wsnackshop.controller.base.BaseController;
import com.nnnu.wsnackshop.pojo.dto.AddAddressDTO;
import com.nnnu.wsnackshop.pojo.dto.UpdateAddressDTO;
import com.nnnu.wsnackshop.pojo.vo.AddressVO;
import com.nnnu.wsnackshop.result.Result;
import com.nnnu.wsnackshop.service.IAddressesService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 用户端-用户收货地址 前端控制器
 * </p>
 *
 * @author zk
 * @since 2025-05-14
 */
@RestController("userAddressesController")
@RequestMapping("/api/user/addresses")
@Slf4j
@Validated
@Tag(name = "用户端-用户收货地址接口")
@RequiredArgsConstructor
public class AddressesController extends BaseController {
    private final IAddressesService addressService;

    @Operation(summary = "获取当前用户所有地址", description = "获取当前登录用户的所有收货地址")
    @GetMapping("/list")
    public Result<List<AddressVO>> getCurrentUserAddresses() {
        Integer currentUserId = getUserId();
        log.info("[用户端] 查询用户({})地址列表", currentUserId);
        List<AddressVO> list = addressService.listByUser(currentUserId.longValue());
        return Result.success(list, MessageConstants.SELECT_OK);
    }

    @Operation(summary = "获取地址详情", description = "获取指定地址的详细信息")
    @GetMapping("/{id}")
    public Result<AddressVO> getAddress(
            @PathVariable @Parameter(description = "地址 ID", in = ParameterIn.PATH) Long id) {
        Integer currentUserId = getUserId();
        log.info("[用户端] 查询用户({})地址详情：{}", currentUserId, id);
        AddressVO vo = addressService.getAddressDetail(id);

        // 验证地址是否属于当前用户
        if (vo != null && !vo.getUserId().equals(currentUserId)) {
            return Result.error(StatusCodeConstants.FORBIDDEN, "无权访问该地址");
        }

        return Result.success(vo, MessageConstants.SELECT_OK);
    }

    @Operation(summary = "新增用户地址", description = "为当前用户新增收货地址")
    @PostMapping
    public Result<Void> createAddress(@Valid @RequestBody @Parameter(description = "新增用户地址 DTO") AddAddressDTO dto) {
        Integer currentUserId = getUserId();
        log.info("[用户端] 用户({})新增地址：{}", currentUserId, dto);

        // 设置当前用户ID
        dto.setUserId(currentUserId);
        addressService.createAddress(dto);
        return Result.success(MessageConstants.ADD_OK);
    }

    @Operation(summary = "更新用户地址", description = "更新当前用户的收货地址")
    @PutMapping
    public Result<Void> updateAddress(@Valid @RequestBody @Parameter(description = "更新用户地址 DTO") UpdateAddressDTO dto) {
        Integer currentUserId = getUserId();
        log.info("[用户端] 用户({})更新地址：{}", currentUserId, dto);

        // 验证地址是否属于当前用户
        AddressVO existingAddress = addressService.getAddressDetail(dto.getId());
        if (existingAddress == null || !existingAddress.getUserId().equals(currentUserId)) {
            return Result.error(StatusCodeConstants.FORBIDDEN, "无权修改该地址");
        }

        addressService.updateAddress(dto);
        return Result.success(MessageConstants.OPERATION_SUCCESSFUL);
    }

    @Operation(summary = "删除用户地址", description = "删除当前用户的收货地址")
    @DeleteMapping("/{id}")
    public Result<Void> deleteAddress(@PathVariable @Parameter(description = "地址 ID", in = ParameterIn.PATH) Long id) {
        Integer currentUserId = getUserId();
        log.info("[用户端] 用户({})删除地址：{}", currentUserId, id);

        // 验证地址是否属于当前用户
        AddressVO existingAddress = addressService.getAddressDetail(id);
        if (existingAddress == null || !existingAddress.getUserId().equals(currentUserId)) {
            return Result.error(StatusCodeConstants.FORBIDDEN, "无权删除该地址");
        }

        addressService.deleteAddresses(List.of(id));
        return Result.success(MessageConstants.OPERATION_SUCCESSFUL);
    }

    @Operation(summary = "设置默认地址", description = "设置当前用户的默认收货地址")
    @PutMapping("/{id}/default")
    public Result<Void> setDefaultAddress(
            @PathVariable @Parameter(description = "地址 ID", in = ParameterIn.PATH) Long id) {
        Integer currentUserId = getUserId();
        log.info("[用户端] 用户({})设置默认地址：{}", currentUserId, id);

        // 验证地址是否属于当前用户
        AddressVO existingAddress = addressService.getAddressDetail(id);
        if (existingAddress == null || !existingAddress.getUserId().equals(currentUserId)) {
            return Result.error(StatusCodeConstants.FORBIDDEN, "无权操作该地址");
        }

        addressService.setDefaultAddress(currentUserId, id);
        return Result.success(MessageConstants.OPERATION_SUCCESSFUL);
    }
}
